package com.dminvoicemanager;

/*Include functions to adjust 
 * stock Quantities by deducting items quantities*/
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.adapters.DM_ItemsList_Adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class DM_AdjustmentDeduction extends Activity {

	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String SALES_ORD_REASON = "fReason";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Adjustment
	private String TEMP_ADJUSTMENT_SUMMARY = "FAdjustmentSummary";
	private String ADJUST_ADDITION_HEADER = "FAdjHed";
	private String ADJUST_ADDITION_DETAILS = "FAdjDet";

	private SQLiteDatabase mydb;
	Button btnstadjustingrefno, btnStockFromLocation,
			btdmstadjustingselectitem, btnadjustmentreason,
			dmstockadjustmentadd, dmstockadjustmentdelete,
			dmstockadjustmentupdate;
	EditText etdmstadjustingdate, etdmstadjustingmanuno, etstockadjustmentFLoc,
			etdmstadjustingitemcaseunit, etdmstadjustingremark,
			etdmstadjustingitemname, etdmstadjustingqoh,
			etdmstadjustingitemprice, etdmstadjustingitemcases,
			etdmstadjustingitempieces, etdmadjustment, etdmadjustmentreason,
			etdminvdunitpriceval,myFilterItemsTC;
	String currentUserStLoad, currentUserPrefixLoad, currentUserLocation,
			stlAgentPrefixType, StlTransTypePrefix, locationDetSummary,
			CurrentLocCode, stLoaditemcode, ReasonRawSummeryResult, reasonCode,
			strLatestAdjustSerial, newAdjustmenrRefNoCode,
			currentAdjustRefCode, strlastId, invDetLastRefNo,
			AdjustRawSummeryResult, LocationItemAdjustRecId,
			CurrentAdjustmentRefId, controlDealCode, PrintTotalAmount,
			currentSumID, currenthedID, caseItemsQtyVal = "0",
			piecesQtyVal = "0", stAdjustCurrentid, tempRepAdjustmentSerialCode,
			PrintcurrentUnitPriceAverage, printItemName, printItemsInCase;
	LinearLayout dmstadjustLocationList, dmstadjustItemsList,
			dmstadjustreasonslist, dmstadjustmaindetails,
			dmstadjustActionButtons;
	int invDetLastSequence = 1, newSequence, ButtonTag, chekVal = 0;;
	long lastId, STOCKITEMSCHK = 0;
	int SAVETAG = 0, UPDATETAG = 0, DELTAG = 0, countC = 44, CLEARTAG = 0,
			CANCELTAG = 0, ONITEMDEL = 0, ONITEMUPDATE = 0, EXITCODE = 0;
	int caseQtyValue = 0, casePiecesValue = 0, casePieQtyValue = 0;
	double TotStLoadCaseItems = 0.0, TotStLoadPieces = 0.0,
			TotPiecesStLoad = 0.0, TotalLoadingValue = 0.0, case_price = 0.0,
			piece_price = 0.0, TotalAmountCurrentAdjust = 0.0,
			AdjustTotQtyVal = 0.0, caseValue = 0.0, piecesValue = 0.0,
			currentAdjustVal = 0.0, adjustedTotVal = 0.0,
			currentAdjustValUpdate = 0.0, DeladjustedTotVal = 0.0;
	final private static int DIALOG_SAVE_STOCK_LOADING = 1;
	final private static int DIALOG_CANCEL_STOCK_LOADING = 2;
	final private static int DIALOG_UNDO_STOCK_LOADING = 3;
	final private static int DIALOG_PRINT_STOCK_LOADING = 4;
	private static final String TAG = null;
	AlertDialog StockLoadingAlert = null;
	private DM_ItemsList_Adapter dbHelper;
	private SimpleCursorAdapter dataAdapter;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	public void AddLocationDetails(View view) {
		Button des = (Button) view;
		locationDetSummary = des.getText().toString();
		String[] Locationsdetail = locationDetSummary.split("/");
		CurrentLocCode = Locationsdetail[0]; // invitemskucode
		String LocName = Locationsdetail[1]; // invitemname
		String LoctCode = Locationsdetail[2]; // invitemsincase
		etstockadjustmentFLoc.setText(LocName);

		dmstadjustLocationList.setVisibility(view.GONE);
		dmstadjustItemsList.setVisibility(view.GONE);
		dmstadjustreasonslist.setVisibility(view.GONE);
		dmstadjustActionButtons.setVisibility(view.VISIBLE);
		dmstadjustmaindetails.setVisibility(view.VISIBLE);

		updateAdjustingLocation();
	}

	private void updateAdjustingLocation() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkUpdateAdjustSummary = null;
		try {
			checkUpdateAdjustSummary = mydb.query(TEMP_ADJUSTMENT_SUMMARY,
					null, "username='" + currentUserStLoad
							+ "' AND currentState='9'  AND AdjustTxnType='50'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (checkUpdateAdjustSummary != null) {
			if (checkUpdateAdjustSummary.getCount() > 0) {
				while (checkUpdateAdjustSummary.moveToNext()) {
					String adjsumrecid = checkUpdateAdjustSummary.getString(0);
					ContentValues valueupdateAdjustSummary = new ContentValues();
					valueupdateAdjustSummary.put("LocCode ", CurrentLocCode);
					valueupdateAdjustSummary.put("LocName ",
							etstockadjustmentFLoc.getText().toString());

					mydb.update(TEMP_ADJUSTMENT_SUMMARY,
							valueupdateAdjustSummary, "adjustsum_id ='"
									+ adjsumrecid + "'", null);
				}
			}
		}
	}

	// ---------Set Items Details in to Main details View Pannel------
	public void AddLocationItemsDetails(View view) {

		Button des = (Button) view;
		String ItemsRawResult = des.getText().toString();
		stLoaditemcode = ItemsRawResult.trim();
		getItemDetails();
		CheckItemWithStock();

		if (chekVal == 0) {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor setStockLocation = null;
			try {
				setStockLocation = mydb.query(ADJUST_ADDITION_DETAILS, null,
						"RefNo='" + currentAdjustRefCode + "'", null, null,
						null, null);
			} catch (Exception e) {
			}
			try {
				if (setStockLocation != null) {
					if (setStockLocation.getCount() > 0) {
						while (setStockLocation.moveToNext()) {
							String stLocItemCode = setStockLocation
									.getString(5);

							if (stLocItemCode.equals(stLoaditemcode)) {
								chekVal = 12;

							} else {

								etdmstadjustingitemname.setText(printItemName);
								etdmstadjustingitemcaseunit
										.setText(printItemsInCase);
								dmstadjustLocationList.setVisibility(view.GONE);
								dmstadjustItemsList.setVisibility(view.GONE);
								dmstadjustreasonslist.setVisibility(view.GONE);
								dmstadjustActionButtons
										.setVisibility(view.VISIBLE);
								dmstadjustmaindetails
										.setVisibility(view.VISIBLE);
								etdmstadjustingitemcases.setText("");
								etdmstadjustingitempieces.setText("");
								setItemsPrice();
								setItemLocationQuantity();

							}
						}
						if (chekVal == 12) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_AdjustmentDeduction.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("INVALID ITEM");
							// Setting Dialog Message
							alertDialog
									.setMessage("Selected Item Adjustment Completed");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											chekVal = 0;
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
					} else {

						etdmstadjustingitemname.setText(printItemName);
						etdmstadjustingitemcaseunit.setText(printItemsInCase);
						dmstadjustLocationList.setVisibility(view.GONE);
						dmstadjustItemsList.setVisibility(view.GONE);
						dmstadjustreasonslist.setVisibility(view.GONE);
						dmstadjustActionButtons.setVisibility(view.VISIBLE);
						dmstadjustmaindetails.setVisibility(view.VISIBLE);
						etdmstadjustingitemcases.setText("");
						etdmstadjustingitempieces.setText("");
						setItemsPrice();
						setItemLocationQuantity();

					}
				} else {

					etdmstadjustingitemname.setText(printItemName);
					etdmstadjustingitemcaseunit.setText(printItemsInCase);
					dmstadjustLocationList.setVisibility(view.GONE);
					dmstadjustItemsList.setVisibility(view.GONE);
					dmstadjustreasonslist.setVisibility(view.GONE);
					dmstadjustActionButtons.setVisibility(view.VISIBLE);
					dmstadjustmaindetails.setVisibility(view.VISIBLE);
					etdmstadjustingitemcases.setText("");
					etdmstadjustingitempieces.setText("");
					setItemsPrice();
					setItemLocationQuantity();

				}
			} catch (Exception e) {
			}
			setStockLocation.close();
			mydb.close();
		}
	};

	private void getItemDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curGetItemsDetails = null;
		try {
			curGetItemsDetails = mydb.query(ITEMS, null, "ItemCode='"
					+ stLoaditemcode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curGetItemsDetails != null) {
			if (curGetItemsDetails.getCount() > 0) {
				while (curGetItemsDetails.moveToNext()) {
					String itemskucode = curGetItemsDetails.getString(1);
					String itemcode = curGetItemsDetails.getString(2);
					printItemName = curGetItemsDetails.getString(4);
					printItemsInCase = curGetItemsDetails.getString(28);

				}
			}
		}
		curGetItemsDetails.close();
		mydb.close();
	}

	private void CheckItemWithStock() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor setQtyonHand = null;
		try {
			setQtyonHand = mydb.query(ITEM_LOC_DETAILS, null, "LocCode='"
					+ CurrentLocCode + "' AND ItemCode='" + stLoaditemcode
					+ "'", null, null, null, null);
		} catch (Exception e) {
		}

		try {
			if (setQtyonHand != null) {
				if (setQtyonHand.getCount() > 0) {
					chekVal = 0;
				} else {
					chekVal = 34;
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("ITEM NOT AVAILABLE");
					// Setting Dialog Message
					alertDialog
							.setMessage("No Items Adjustment Addition.Select Another Item");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									chekVal = 34;
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			}
		} catch (Exception e) {
		}

	}

	// Set selected itel location Quantity on hand
	private void setItemLocationQuantity() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor setQtyonHand = null;
		try {
			setQtyonHand = mydb.query(ITEM_LOC_DETAILS, null, "LocCode='"
					+ CurrentLocCode + "' AND ItemCode='" + stLoaditemcode
					+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (setQtyonHand != null) {
			if (setQtyonHand.getCount() > 0) {
				while (setQtyonHand.moveToNext()) {
					String qtyOnHand = setQtyonHand.getString(3);
					etdmstadjustingqoh.setText(qtyOnHand);
				}
			} else if (setQtyonHand.getCount() <= 0) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_AdjustmentDeduction.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("ITEM NOT AVAILABLE");
				// Setting Dialog Message
				alertDialog
						.setMessage("Select Item not avaialble in selected location...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
			}
		}
		setQtyonHand.close();
		mydb.close();
	}

	private void setItemsPrice() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		String[] cols = { "ItemCode" };
		Cursor chkItemPrice = null;

		try {
			String query = "SELECT ITP.ItemCode,ITP.PrilCode, ITP.Price, ITM.AvgPrice from fItemPri ITP, fItems ITM Where ITP.ItemCode = ITM.ItemCode order by ITP.ItemCode";
			chkItemPrice = mydb.rawQuery(query, null);
		} catch (Exception e1) {
		}

		if (chkItemPrice != null) {
			if (chkItemPrice.getCount() > 0) {
				while (chkItemPrice.moveToNext()) {
					String itemsUnitsPerCase = etdmstadjustingitemcaseunit
							.getText().toString();
					double currentUnitQty = Double
							.parseDouble(itemsUnitsPerCase);
					String itemcodep = chkItemPrice.getString(0);
					String itempricatcode = chkItemPrice.getString(1);
					String pricecat = itempricatcode.substring(0, 1);
					String itemprice = chkItemPrice.getString(2);
					String caseAvgPrice = chkItemPrice.getString(3);
					Log.v(TAG, "caseitemprice:" + itemprice);
					Log.v(TAG, "caseAvgPrice:" + caseAvgPrice);
					// cost price = average case price
					double currentUnitPriceOri = Double
							.parseDouble(caseAvgPrice);
					currentUnitPriceOri = Math.round(currentUnitPriceOri * 100) / 100.0d;
					String PrintcurrentUnitPriceRegular = Double
							.toString(currentUnitPriceOri);

					double currentUnitPrice = Double.parseDouble(caseAvgPrice);
					currentUnitPrice = Math.round(currentUnitPrice * 100) / 100.0d;
					String PrintcurrentUnitPriceAvg = Double
							.toString(currentUnitPrice);
					double currentItemsPrice = currentUnitPrice
							/ currentUnitQty;
					currentItemsPrice = Math.round(currentItemsPrice * 100) / 100.0d;
					String PrintcurrentItemsPrice = Double
							.toString(currentItemsPrice);
					itemcodep.trim();

					if (itemcodep.equals(stLoaditemcode)) {

						if (itempricatcode.equals("WSP001")) {
							PrintcurrentUnitPriceAverage = PrintcurrentUnitPriceRegular
									.trim();
							etdmstadjustingitemprice
									.setText(PrintcurrentItemsPrice);
							etdminvdunitpriceval
									.setText(PrintcurrentUnitPriceAvg);
						} else {

						}
						PrintcurrentUnitPriceAverage = PrintcurrentUnitPriceRegular
								.trim();
						etdmstadjustingitemprice
								.setText(PrintcurrentItemsPrice);
						etdminvdunitpriceval.setText(PrintcurrentUnitPriceAvg);
					} else {

					}
				}
			}
		}
		chkItemPrice.close();
		mydb.close();
	}

	// Display Selected Reason
	public void AddResonsDetails(View view) {
		Button desReason = (Button) view;
		ReasonRawSummeryResult = desReason.getText().toString();
		String[] reasonsdetail = ReasonRawSummeryResult.split("/");
		reasonCode = reasonsdetail[0];
		String reasonDes = reasonsdetail[1];
		etdmadjustmentreason.setText(reasonDes);

		dmstadjustLocationList.setVisibility(view.GONE);
		dmstadjustItemsList.setVisibility(view.GONE);
		dmstadjustreasonslist.setVisibility(view.GONE);
		dmstadjustActionButtons.setVisibility(view.VISIBLE);
		dmstadjustmaindetails.setVisibility(view.VISIBLE);
	}

	// Preview previous Adjustment Details
	public void ShowAdjustRecordDetails(View view) {
		Button adjustRecord = (Button) view;
		AdjustRawSummeryResult = adjustRecord.getText().toString();
		String[] AdjustRawdetail = AdjustRawSummeryResult.split("/");
		LocationItemAdjustRecId = AdjustRawdetail[0];
		stLoaditemcode = AdjustRawdetail[1];
		String CaseQty = AdjustRawdetail[2];
		String PiceQty = AdjustRawdetail[3];
		String CostPrice = AdjustRawdetail[4];
		reasonCode = AdjustRawdetail[5];
		String ItemName = AdjustRawdetail[6];
		String QOH = AdjustRawdetail[7];
		String ReaName = AdjustRawdetail[8];
		String CaseUnits = AdjustRawdetail[9];
		String CasePrice = AdjustRawdetail[10];

		etdmstadjustingitemname.setText(ItemName);
		etdmstadjustingqoh.setText(QOH);
		etdmstadjustingitemcaseunit.setText(CaseUnits);
		etdmstadjustingitemprice.setText(CostPrice);
		etdminvdunitpriceval.setText(CasePrice);
		etdmstadjustingitemcases.setText(CaseQty);
		etdmstadjustingitempieces.setText(PiceQty);
		etdmadjustmentreason.setText(ReaName);

		dmstockadjustmentadd.setEnabled(false);
		dmstockadjustmentdelete.setEnabled(true);
		dmstockadjustmentupdate.setEnabled(true);
	}

	public void btnStockLocationBack(View view) {
		dmstadjustLocationList.setVisibility(view.GONE);
		dmstadjustItemsList.setVisibility(view.GONE);
		dmstadjustreasonslist.setVisibility(view.GONE);
		dmstadjustmaindetails.setVisibility(view.VISIBLE);
		dmstadjustActionButtons.setVisibility(view.VISIBLE);
	}

	// ******Save Adjustment Addition*********
	public void btnSaveLoding(View view) {
		checkItemsAvailable();
		if (STOCKITEMSCHK == 101) {
			ButtonTag = 2;
			SaveMainStockLoading();
		} else if (STOCKITEMSCHK == 102) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_AdjustmentDeduction.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("ITEMS ADJUSTMENT");
			// Setting Dialog Message
			alertDialog.setMessage("No Items Adjustment Addition..");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// ******Check current item avalability****
	private void checkItemsAvailable() {
		// TODO Auto-generated method stub
		String currentStLoadCodeRef = btnstadjustingrefno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkItems = null;
		try {
			curChkItems = mydb
					.query(ADJUST_ADDITION_DETAILS, null, "RefNo='"
							+ currentStLoadCodeRef.trim() + "'", null, null,
							null, null);
		} catch (Exception e) {
		}
		if (curChkItems != null) {
			if (curChkItems.getCount() > 0) {
				STOCKITEMSCHK = 101;
			} else {
				STOCKITEMSCHK = 102;
			}
		}
		curChkItems.close();
		mydb.close();
	}

	private void SaveMainStockLoading() {
		// TODO Auto-generated method stub
		int DELTAG = 0;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStockAdjustmentMain = null;
		try {
			saveStockAdjustmentMain = mydb.query(TEMP_ADJUSTMENT_SUMMARY, null,
					"username='" + currentUserStLoad
							+ "' AND currentState='9'  AND AdjustTxnType='51'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (saveStockAdjustmentMain != null) {
			if (saveStockAdjustmentMain.getCount() > 0) {
				while (saveStockAdjustmentMain.moveToNext()) {
					ContentValues valueupdateStAdjustState = new ContentValues();
					String stAdjustSumID = saveStockAdjustmentMain.getString(0);
					strLatestAdjustSerial = saveStockAdjustmentMain
							.getString(3);
					valueupdateStAdjustState.put("currentState", "0");
					valueupdateStAdjustState.put("activeMode", "2");
					mydb.update(TEMP_ADJUSTMENT_SUMMARY,
							valueupdateStAdjustState, "adjustsum_id ='"
									+ stAdjustSumID + "'", null);
					createNewAdjustmentAdditionSum();

					if (ButtonTag == 2) {

						try {
							showDialog(DIALOG_SAVE_STOCK_LOADING);
						} catch (Exception ex) {
							ex.printStackTrace();
						}

						/*
						 * final AlertDialog alertDialog = new
						 * AlertDialog.Builder(
						 * DM_AdjustmentDeduction.this).create(); // Setting
						 * Dialog Title
						 * alertDialog.setTitle("SAVE STOCK ADJUSTMENT"); //
						 * Setting Dialog Message alertDialog .setMessage(
						 * "Stock Adjustment Deduction Saved Successfully..");
						 * // Setting Icon to Dialog
						 * alertDialog.setIcon(R.drawable.warning); // Setting
						 * OK Button alertDialog.setButton("OK", new
						 * DialogInterface.OnClickListener() { public void
						 * onClick(DialogInterface dialog, int which) {
						 * alertDialog.dismiss(); } }); // Showing Alert Message
						 * alertDialog.show(); return;
						 */
					}

				}

			}
		}
		saveStockAdjustmentMain.close();
		mydb.close();
	}

	private void createNewAdjustmentAdditionSum() {
		// TODO Auto-generated method stub
		int tempRepStLoadSerialId = Integer.parseInt(strLatestAdjustSerial);
		int newStLoadSerialId = tempRepStLoadSerialId + 1;
		strLatestAdjustSerial = Integer.toString(newStLoadSerialId);

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		newAdjustmenrRefNoCode = StlTransTypePrefix.trim()
				+ stlAgentPrefixType.trim() + currentUserPrefixLoad;
		try {
			ContentValues addnewAdjustment = new ContentValues();
			addnewAdjustment.put("username", currentUserStLoad);

			try {
				if (strLatestAdjustSerial.length() == 1) {
					String newInvNumberStr = "00000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 2) {
					String newInvNumberStr = "0000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 3) {
					String newInvNumberStr = "000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 4) {
					String newInvNumberStr = "00" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 5) {
					String newInvNumberStr = "0" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			addnewAdjustment.put("refSerial", strLatestAdjustSerial);
			addnewAdjustment.put("refCode", currentAdjustRefCode);
			addnewAdjustment.put("currentState", "9");
			addnewAdjustment.put("activeMode", "0");
			addnewAdjustment.put("LocCode", "0");
			addnewAdjustment.put("LocName", "");
			addnewAdjustment.put("TotalAmount", "0.0");
			addnewAdjustment.put("ManuRefNo", "");
			addnewAdjustment.put("AdjustTxnType", "51");
			mydb.insert(TEMP_ADJUSTMENT_SUMMARY, null, addnewAdjustment);

		} catch (Exception e) {
			// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
		updateFcompanyBranch();
		updateMainStocks();
		mydb.close();
	}

	// ******Update Stock Location Items Quantity*******
	private void updateMainStocks() {
		// TODO Auto-generated method stub
		String currentStLoadCodeRef = btnstadjustingrefno.getText().toString();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor stockLoaddetQty = null;
		Cursor saveStockQuantityMain = null;
		try {
			stockLoaddetQty = mydb.query(ADJUST_ADDITION_DETAILS, null,
					"RefNo='" + currentStLoadCodeRef + "'", null, null, null,
					null);

		} catch (Exception e) {
		}
		if (stockLoaddetQty != null) {
			if (stockLoaddetQty.getCount() > 0) {
				while (stockLoaddetQty.moveToNext()) {
					String RefNo = stockLoaddetQty.getString(1);
					String ItemCode = stockLoaddetQty.getString(5);
					String Qty = stockLoaddetQty.getString(8);
					AdjustTotQtyVal = Double.parseDouble(Qty);

					String[] selectstate = { "LocCode", "ItemCode" };
					try {
						saveStockQuantityMain = mydb.query(ITEM_LOC_DETAILS,
								null, "LocCode='" + CurrentLocCode
										+ "' AND ItemCode='" + ItemCode + "'",
								null, null, null, null);

					} catch (Exception e) {
					}
					if (saveStockQuantityMain != null) {
						if (saveStockQuantityMain.getCount() > 0) {
							while (saveStockQuantityMain.moveToNext()) {
								ContentValues valueupdateMainQty = new ContentValues();
								String LocCodechk = saveStockQuantityMain
										.getString(1);
								String ItemCodechk = saveStockQuantityMain
										.getString(2);
								String LocQtychkr = saveStockQuantityMain
										.getString(3);
								String RecordIdhkr = saveStockQuantityMain
										.getString(4);

								Double currentLovQTY = Double
										.parseDouble(LocQtychkr);
								Double ItemAdjustedQty = currentLovQTY
										- AdjustTotQtyVal;
								String ItemAdjustedQtyVal = Double
										.toString(ItemAdjustedQty);
								valueupdateMainQty.put("QOH",
										ItemAdjustedQtyVal);
								valueupdateMainQty.put("syncRec", "1");
								mydb.update(ITEM_LOC_DETAILS,
										valueupdateMainQty, "RecordId ='"
												+ RecordIdhkr + "'", null);
							}
						} else {
							Toast.makeText(getApplicationContext(),
									"*****NO LOC ITEM*******",
									Toast.LENGTH_SHORT).show();
						}
					}
				}
			} else {
				Toast.makeText(getApplicationContext(), "***No Records***",
						Toast.LENGTH_SHORT).show();
			}
		}
		clearFieldsAdjustment();
		SAVETAG = 0;
		DELTAG = 0;
		saveStockQuantityMain.close();
		stockLoaddetQty.close();
		mydb.close();

	}

	private void updateFcompanyBranch() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='SADJD' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", strLatestAdjustSerial);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}
		selectUserSerial.close();
		mydb.close();
	}

	public void btnSaveInvoiceAccept(View view) {
		if (btnstadjustingrefno.length() != 0) {

			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			StockLoadingAlert.dismiss();
			finish();

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_AdjustmentDeduction.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("STOCK ADJUSTMENT ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Stock Adjustment Not Found");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	public void ExitFromForm(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		StockLoadingAlert.dismiss();
		finish();
	}

	// ==============Undo Invoice====================
	public void btnUndoLoading(View view) {
		if (btnstadjustingrefno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_STOCK_LOADING);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_AdjustmentDeduction.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT STOCK UNLOADING");
			// Setting Dialog Message
			alertDialog.setMessage("Select Valid Stock Adjustment");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		StockLoadingAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		// updateStLoadUndoState();
		CLEARTAG = 22;
		clearFieldsAdjustment();
		updateAdjustmentUndoState();
		StockLoadingAlert.dismiss();
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		// CLEARTAG = 22;
		EXITCODE = 99;
		clearFieldsAdjustment();
		updateAdjustmentUndoState();

	}

	private void updateAdjustmentUndoState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String columsup[] = { "stlrepusername", "stLoadActive" };
		Cursor undoAdjustsSumMain = null;
		try {
			undoAdjustsSumMain = mydb.query(TEMP_ADJUSTMENT_SUMMARY, null,
					"username='" + currentUserStLoad
							+ "' AND currentState='9' AND AdjustTxnType='51'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (undoAdjustsSumMain != null) {
			if (undoAdjustsSumMain.getCount() > 0) {
				while (undoAdjustsSumMain.moveToNext()) {
					ContentValues valueupdateStLoadState = new ContentValues();
					stAdjustCurrentid = undoAdjustsSumMain.getString(0);
					tempRepAdjustmentSerialCode = undoAdjustsSumMain
							.getString(2);

					valueupdateStLoadState.put("LocCode", "0");
					valueupdateStLoadState.put("LocName", "");
					valueupdateStLoadState.put("TotalAmount", "0");
					valueupdateStLoadState.put("ManuRefNo", "");
					mydb.update(TEMP_ADJUSTMENT_SUMMARY,
							valueupdateStLoadState, "adjustsum_id ='"
									+ stAdjustCurrentid + "'", null);
				}

			}

		}
		undoAdjustsSumMain.close();
		mydb.close();
		deleteStockLoadingItems();
		if (EXITCODE == 99) {
			forceExit();
		}
	}

	private void forceExit() {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(this, DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		DM_AdjustmentDeduction.this.finish();
		finish();
	}

	private void deleteStockLoadingItems() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor adjustmentHeadItemsDel = null;
		try {
			adjustmentHeadItemsDel = mydb.query(ADJUST_ADDITION_HEADER, null,
					"RefNo='" + tempRepAdjustmentSerialCode + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		if (adjustmentHeadItemsDel != null) {
			if (adjustmentHeadItemsDel.getCount() > 0) {
				while (adjustmentHeadItemsDel.moveToNext()) {
					String tempRepStLoadrefcode = adjustmentHeadItemsDel
							.getString(1);
					mydb.delete(ADJUST_ADDITION_HEADER, "RefNo ='"
							+ tempRepStLoadrefcode + "'", null);
				}
			}
		}

		Cursor adjustmentDetailItemsDel = null;
		try {
			adjustmentDetailItemsDel = mydb.query(ADJUST_ADDITION_DETAILS,
					null, "RefNo='" + tempRepAdjustmentSerialCode + "'", null,
					null, null, null);
		} catch (Exception e) {
		}

		if (adjustmentDetailItemsDel != null) {
			if (adjustmentDetailItemsDel.getCount() > 0) {
				while (adjustmentDetailItemsDel.moveToNext()) {
					String tempRepStLoadrefcode = adjustmentDetailItemsDel
							.getString(1);
					mydb.delete(ADJUST_ADDITION_DETAILS, "RefNo ='"
							+ tempRepStLoadrefcode + "'", null);
				}
			}
		}
		ListAdjustingItems();
		adjustmentHeadItemsDel.close();
		adjustmentDetailItemsDel.close();
		mydb.close();
	}

	// *********Cancel Adjustments*******************
	public void btnCanclloading(View view) {
		checkAdjustmentSaved();
		if (CANCELTAG == 45) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_AdjustmentDeduction.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("STOCK ADJUSTMENT NOT SAVED");
			// Setting Dialog Message
			alertDialog
					.setMessage("Selected Stock Adjustment Not Saved.Select Valid Stock Adjustment To Cancel");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CANCELTAG = 0;
					alertDialog.dismiss();
				}
			});
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			checkItemsAvailable();
			if (STOCKITEMSCHK == 101) {
				if (btnstadjustingrefno.length() != 0) {
					try {
						ButtonTag = 3;
						showDialog(DIALOG_CANCEL_STOCK_LOADING);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT STOCK ADJUSTMENT");
					// Setting Dialog Message
					alertDialog.setMessage("Select Valid Stock Adjustment");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			} else if (STOCKITEMSCHK == 102) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_AdjustmentDeduction.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("ITEMS ADJUSTMENT");
				// Setting Dialog Message
				alertDialog.setMessage("No Items For Stock Adjustment");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}

	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		StockLoadingAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		// cancelNewStockLoadingRec();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	private void checkAdjustmentSaved() {
		// TODO Auto-generated method stub
		String CurrentAdjustmentRefNo = btnstadjustingrefno.getText()
				.toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentAdjustmentCur = null;
		try {
			CurrentAdjustmentCur = mydb
					.query(TEMP_ADJUSTMENT_SUMMARY,
							null,
							"username='"
									+ currentUserStLoad
									+ "' AND refCode='"
									+ CurrentAdjustmentRefNo
									+ "' AND currentState !='9' AND AdjustTxnType='51'",
							null, null, null, null);

		} catch (Exception e) {
		}
		if (CurrentAdjustmentCur != null) {
			if (CurrentAdjustmentCur.getCount() > 0) {
				while (CurrentAdjustmentCur.moveToNext()) {
					String stLoadActive = CurrentAdjustmentCur.getString(7);
					if (stLoadActive.equals("9")) {
						CANCELTAG = 45;
					}

				}
			}
		}
		CurrentAdjustmentCur.close();
		mydb.close();
	}

	// =================================================================
	public void btnPrintStloading(View view) {
		try {
			showDialog(DIALOG_PRINT_STOCK_LOADING);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// Undo Invoice Handling
	public void btnPrintInvoiceCancel(View view) {
		StockLoadingAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		StockLoadingAlert.dismiss();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_adjustment_deduction);

		dbHelper = new DM_ItemsList_Adapter(this);
		dbHelper.open();

		dmstadjustLocationList = (LinearLayout) findViewById(R.id.dmstadjustLocationList);
		dmstadjustItemsList = (LinearLayout) findViewById(R.id.dmstadjustItemsList);
		dmstadjustreasonslist = (LinearLayout) findViewById(R.id.dmstadjustreasonslist);
		dmstadjustmaindetails = (LinearLayout) findViewById(R.id.dmstadjustmaindetails);
		dmstadjustActionButtons = (LinearLayout) findViewById(R.id.dmstadjustActionButtons);

		btnstadjustingrefno = (Button) findViewById(R.id.btnstadjustingrefno);
		btnStockFromLocation = (Button) findViewById(R.id.btnStockFromLocation);
		btdmstadjustingselectitem = (Button) findViewById(R.id.btdmstadjustingselectitem);
		btnadjustmentreason = (Button) findViewById(R.id.btnadjustmentreason);

		// Main Activity Grid Controller Button
		dmstockadjustmentadd = (Button) findViewById(R.id.dmstockadjustmentadd);
		dmstockadjustmentdelete = (Button) findViewById(R.id.dmstockadjustmentdelete);
		dmstockadjustmentupdate = (Button) findViewById(R.id.dmstockadjustmentupdate);

		etdmstadjustingdate = (EditText) findViewById(R.id.etdmstadjustingdate);
		etdmstadjustingmanuno = (EditText) findViewById(R.id.etdmstadjustingmanuno);
		etstockadjustmentFLoc = (EditText) findViewById(R.id.etstockadjustmentFLoc);
		etdmstadjustingremark = (EditText) findViewById(R.id.etdmstadjustingremark);
		etdmstadjustingitemname = (EditText) findViewById(R.id.etdmstadjustingitemname);
		etdmstadjustingqoh = (EditText) findViewById(R.id.etdmstadjustingqoh);
		etdmstadjustingitemprice = (EditText) findViewById(R.id.etdmstadjustingitemprice);
		etdmstadjustingitemcases = (EditText) findViewById(R.id.etdmstadjustingitemcases);
		etdmstadjustingitemcases.addTextChangedListener(invoiceMaxCasesWatcher);
		etdmstadjustingitempieces = (EditText) findViewById(R.id.etdmstadjustingitempieces);
		etdmstadjustingitempieces.addTextChangedListener(checkPiecesValidation);

		etdmadjustmentreason = (EditText) findViewById(R.id.etdmadjustmentreason);
		etdmstadjustingitemcaseunit = (EditText) findViewById(R.id.etdmstadjustingitemcaseunit);
		etdminvdunitpriceval = (EditText) findViewById(R.id.etdminvdunitpriceval);
		myFilterItemsTC = (EditText) findViewById(R.id.dminvfilteritems);
		
		currentUserStLoadChk();// Check Current User
		stLoadingAgentPrefix();// Check Current Agent Prefix
		stLoadingTransType();// Check Current Trans Type
		checkLatestAdjustmentSerial();// Check latest Reference Serial
		// checkLatestAdjustmentState();
		populateStockLoadLocationList();// Stock Load Location List
		populateItemsDetailsList();// Stock Load Items List
		populateReasonsDetailsList();// Stock Load Reason List
		// viewCurrentAdjustmetRecords();
		btnStockFromLocation.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dmstadjustLocationList.setVisibility(view.VISIBLE);
				dmstadjustItemsList.setVisibility(view.GONE);
				dmstadjustreasonslist.setVisibility(view.GONE);
				dmstadjustmaindetails.setVisibility(view.GONE);
				dmstadjustActionButtons.setVisibility(view.GONE);
			}

		});

		btdmstadjustingselectitem
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						if (etstockadjustmentFLoc.length() != 0) {
							dmstadjustLocationList.setVisibility(view.GONE);
							dmstadjustItemsList.setVisibility(view.VISIBLE);
							dmstadjustreasonslist.setVisibility(view.GONE);
							dmstadjustmaindetails.setVisibility(view.GONE);
							dmstadjustActionButtons.setVisibility(view.GONE);
						} else {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_AdjustmentDeduction.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("SELECT LOCATION");
							// Setting Dialog Message
							alertDialog
									.setMessage("Select location for stock adjustment addition...");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
						}

					}

				});

		btnadjustmentreason.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dmstadjustLocationList.setVisibility(view.GONE);
				dmstadjustItemsList.setVisibility(view.GONE);
				dmstadjustreasonslist.setVisibility(view.VISIBLE);
				dmstadjustmaindetails.setVisibility(view.GONE);
				dmstadjustActionButtons.setVisibility(view.GONE);
			}

		});

		// ----------------Add new Adjustment to DB-----------------
		dmstockadjustmentadd.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (etstockadjustmentFLoc.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT LOCATION");
					// Setting Dialog Message
					alertDialog
							.setMessage("Select location for stock adjustment addition...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
				} else if (etdmstadjustingitemname.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT AN ITEM");
					// Setting Dialog Message
					alertDialog
							.setMessage("Select an Item for stock adjustment addition...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
				} else if (etdmstadjustingitemcases.length() == 0
						&& etdmstadjustingitempieces.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("ENTER ADJUSTING QTY");
					// Setting Dialog Message
					alertDialog
							.setMessage("Eneter adjustment addition quantity for the selected item..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
				} else if (etdmadjustmentreason.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("ENTER REASON");
					// Setting Dialog Message
					alertDialog
							.setMessage("Eneter adjustment addition reason..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
				}

				else {
					double CasesQtyVal = 0.00;
					double PiecesQtyVal = 0.00;
					if (etdmstadjustingitemcases.length() != 0) {
						String chkCasesQtyStr = etdmstadjustingitemcases
								.getText().toString();
						CasesQtyVal = Double.parseDouble(chkCasesQtyStr
								.replaceAll("[,]", ""));
					}
					if (etdmstadjustingitempieces.length() != 0) {
						String chkPiecesQtyStr = etdmstadjustingitempieces
								.getText().toString();
						PiecesQtyVal = Double.parseDouble(chkPiecesQtyStr
								.replaceAll("[,]", ""));
					}

					if (CasesQtyVal > 0 || PiecesQtyVal > 0) {
						saveNewAdjustmentAddition();
					} else {
						chkCasePiecesQuantity();
					}
				}
			}
		});

		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		// Delete Stock Load Item From List
		dmstockadjustmentdelete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ONITEMDEL = 64;
				DELTAG = 88;
				// item init QTY
				String stl_item_unit_qty = etdmstadjustingitemcaseunit
						.getText().toString();
				Double stl_item_unit_qty_val = Double
						.parseDouble(stl_item_unit_qty);
				if (etdmstadjustingitemcases.length() != 0) {
					String Loading_case_qty = etdmstadjustingitemcases
							.getText().toString();
					Double Stl_case_qty = Double.parseDouble(Loading_case_qty);
					TotStLoadCaseItems = Stl_case_qty * stl_item_unit_qty_val;
				}

				if (etdmstadjustingitempieces.length() != 0) {
					String Loading_piece_qty = etdmstadjustingitempieces
							.getText().toString();
					Double Stl_piece_qty = Double
							.parseDouble(Loading_piece_qty);
					TotStLoadPieces = Stl_piece_qty;
				}
				TotPiecesStLoad = TotStLoadCaseItems + TotStLoadPieces;

				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectDelitem = null;
				try {
					selectDelitem = mydb.query(ADJUST_ADDITION_DETAILS, null,
							"RefNo='" + currentAdjustRefCode
									+ "'AND ItemCode='" + stLoaditemcode + "'",
							null, null, null, null);
				} catch (Exception e) {
				}
				try {
					if (selectDelitem != null) {
						if (selectDelitem.getCount() > 0) {
							while (selectDelitem.moveToNext()) {
								String currentTotVal = selectDelitem
										.getString(10);
								currentAdjustValUpdate = Double
										.parseDouble(currentTotVal);
								Log.v(TAG, "PRE ORIGINAL DEL:"
										+ currentAdjustValUpdate);
								updateTotAmountdelUpdate();
								mydb.delete(
										ADJUST_ADDITION_DETAILS,
										"fadjdet_id ='"
												+ LocationItemAdjustRecId + "'",
										null);
							}
						}
					}

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				ensbleAndDisButtons();
				btnStockFromLocation.setEnabled(false);
				selectDelitem.close();
				mydb.close();

				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_AdjustmentDeduction.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("DELETE ITEM");
				// Setting Dialog Message
				alertDialog.setMessage("Delete Item Success...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								ListAdjustingItems();
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
				// populateStockLoadList();
			}
		});

		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		dmstockadjustmentupdate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				double CasesQtyVal = 0.00;
				double PiecesQtyVal = 0.00;
				if (etdmstadjustingitemcases.length() != 0) {
					String chkCasesQtyStr = etdmstadjustingitemcases.getText()
							.toString();
					CasesQtyVal = Double.parseDouble(chkCasesQtyStr.replaceAll(
							"[,]", ""));
				}
				if (etdmstadjustingitempieces.length() != 0) {
					String chkPiecesQtyStr = etdmstadjustingitempieces
							.getText().toString();
					PiecesQtyVal = Double.parseDouble(chkPiecesQtyStr
							.replaceAll("[,]", ""));
				}

				if (CasesQtyVal > 0 || PiecesQtyVal > 0) {
					updateAdjustmentAddition();
				} else {
					chkCasePiecesQuantity();
				}
			}

			private void updateAdjustmentAddition() {
				// TODO Auto-generated method stub
				ONITEMUPDATE = 54;
				// Previous Total value calculation for selected Item
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectDelitem = null;
				try {
					selectDelitem = mydb.query(ADJUST_ADDITION_DETAILS, null,
							"RefNo='" + currentAdjustRefCode
									+ "'AND ItemCode='" + stLoaditemcode + "'",
							null, null, null, null);
				} catch (Exception e) {
				}
				try {
					if (selectDelitem != null) {
						if (selectDelitem.getCount() > 0) {
							while (selectDelitem.moveToNext()) {
								String currentTotVal = selectDelitem
										.getString(10);
								currentAdjustValUpdate = Double
										.parseDouble(currentTotVal);
								Log.v(TAG, "PRE ORIGINAL:"
										+ currentAdjustValUpdate);

							}
						}
					}

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				try {
					// case price
					String stl_case_price = etdminvdunitpriceval.getText()
							.toString();
					Double stl_case_price_val = Double
							.parseDouble(stl_case_price);
					// item price
					String stl_item_price = etdmstadjustingitemprice.getText()
							.toString();
					Double stl_item_price_val = Double
							.parseDouble(stl_item_price);
					// item init QTY
					String stl_item_unit_qty = etdmstadjustingitemcaseunit
							.getText().toString();
					Double stl_item_unit_qty_val = Double
							.parseDouble(stl_item_unit_qty);

					// TotStLoadCaseItems=0.0,TotStLoadPieces=0.0;
					if (etdmstadjustingitemcases.length() != 0) {
						String Loading_case_qty = etdmstadjustingitemcases
								.getText().toString();
						Double Stl_case_qty = Double
								.parseDouble(Loading_case_qty);
						case_price = Stl_case_qty * stl_case_price_val;
						TotStLoadCaseItems = Stl_case_qty
								* stl_item_unit_qty_val;
					}
					if (etdmstadjustingitempieces.length() != 0) {
						String Loading_piece_qty = etdmstadjustingitempieces
								.getText().toString();
						Double Stl_piece_qty = Double
								.parseDouble(Loading_piece_qty);
						piece_price = Stl_piece_qty * stl_item_price_val;
						TotStLoadPieces = Stl_piece_qty;
					}
					TotalLoadingValue = case_price + piece_price;
					Log.v(TAG, "NEW UPDATE VAL:" + TotalLoadingValue);
					TotPiecesStLoad = TotStLoadCaseItems + TotStLoadPieces;
					updateTotAmountdelUpdate();
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}
				// Pre Calculations for cases Pieces
				String casePieces = etdmstadjustingitemcaseunit.getText()
						.toString();
				casePieQtyValue = Integer.parseInt(casePieces);

				if (etdmstadjustingitemcases.length() != 0) {
					String caseQtyStr = etdmstadjustingitemcases.getText()
							.toString();
					caseQtyValue = Integer.parseInt(caseQtyStr);
				}
				if (etdmstadjustingitempieces.length() != 0) {
					String piecesQtyStr = etdmstadjustingitempieces.getText()
							.toString();
					casePiecesValue = Integer.parseInt(piecesQtyStr);
				}
				if (casePiecesValue >= casePieQtyValue) {
					Integer newCasesQty = casePiecesValue / casePieQtyValue;
					caseQtyValue = caseQtyValue + newCasesQty;

					casePiecesValue = (casePiecesValue - (newCasesQty * casePieQtyValue));
				}
				// Updating Invoice Details
				try {
					ContentValues newStockLoadRecDetailUpdateP = new ContentValues();
					// Calculate Total Quantity in cases and pieces
					caseItemsQtyVal = Integer.toString(caseQtyValue);
					piecesQtyVal = Integer.toString(casePiecesValue);
					String caseUnitsVal = etdmstadjustingitemcaseunit.getText()
							.toString();
					String pieceAmount = etdmstadjustingitemprice.getText()
							.toString();
					if (etdmstadjustingitemcases.length() != 0) {
						caseValue = Double.parseDouble(caseItemsQtyVal);
					}
					if (etdmstadjustingitempieces.length() != 0) {
						piecesValue = Double.parseDouble(piecesQtyVal);
					}

					double unitsValue = Double.parseDouble(caseUnitsVal);
					double pieceAmountValue = Double.parseDouble(pieceAmount);
					double TotalPiecesQTY = (caseValue * unitsValue)
							+ piecesValue;
					String PrintTotalPiecesQTY = Double
							.toString(TotalPiecesQTY);
					double TotalAmount = pieceAmountValue * TotalPiecesQTY;
					String PrintTotalAmount = Double.toString(TotalAmount);
					newStockLoadRecDetailUpdateP.put("CaseQty ",
							caseItemsQtyVal);
					newStockLoadRecDetailUpdateP.put("PiceQty ", piecesQtyVal);
					newStockLoadRecDetailUpdateP.put("Qty ",
							PrintTotalPiecesQTY);
					newStockLoadRecDetailUpdateP.put("CostPrice",
							PrintcurrentUnitPriceAverage);
					newStockLoadRecDetailUpdateP.put("Amt ", PrintTotalAmount);
					newStockLoadRecDetailUpdateP.put("ReaCode ", reasonCode);
					newStockLoadRecDetailUpdateP.put("ItemName ",
							etdmstadjustingitemname.getText().toString());
					newStockLoadRecDetailUpdateP.put("QOH ", etdmstadjustingqoh
							.getText().toString());
					newStockLoadRecDetailUpdateP.put("ReaName ",
							etdmadjustmentreason.getText().toString());
					newStockLoadRecDetailUpdateP.put("CaseUnits ",
							etdmstadjustingitemcaseunit.getText().toString());
					newStockLoadRecDetailUpdateP.put("CasePrice ",
							etdminvdunitpriceval.getText().toString());
					mydb.update(ADJUST_ADDITION_DETAILS,
							newStockLoadRecDetailUpdateP, "fadjdet_id ='"
									+ LocationItemAdjustRecId + "'", null);
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				// Calling After saving one record in to Stock Loading Tables
				btnStockFromLocation.setEnabled(false);
				ensbleAndDisButtons();
				clearFieldsAdjustment();
				ListAdjustingItems();

				mydb.close();
			}
		});

	}

	protected void chkCasePiecesQuantity() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_AdjustmentDeduction.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("ENTER ITEM QTY");
		// Setting Dialog Message
		alertDialog
				.setMessage("Enter Cases / Pieces Quantities For Selected Item..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	private TextWatcher invoiceMaxCasesWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (etdmstadjustingitemcases.length() != 0) {
				double inputQoh = 0.0, inputCases = 0.0, inputPieces = 0.0, CaseUnitAmountVal = 0.0;
				String CaseUnitAmount = etdmstadjustingitemcaseunit.getText()
						.toString();
				String Item_qoh = etdmstadjustingqoh.getText().toString();
				inputQoh = Double.parseDouble(Item_qoh);
				String Item_PerCase = etdmstadjustingitemcases.getText()
						.toString();
				inputCases = Double.parseDouble(Item_PerCase);
				CaseUnitAmountVal = Double.parseDouble(CaseUnitAmount);
				if (etdmstadjustingitempieces.length() != 0) {
					String Item_Pieces = etdmstadjustingitemcases.getText()
							.toString();
					inputPieces = Double.parseDouble(Item_Pieces);
				}

				double totalPiecesAdjustDeduct = ((inputCases * CaseUnitAmountVal) + inputPieces);

				if (totalPiecesAdjustDeduct > inputQoh) {
					etdmstadjustingitemcases.setText("");
					etdmstadjustingitempieces.setText("");
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_AdjustmentDeduction.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("INVALID ADJUSTMENT");
					// Setting Dialog Message
					alertDialog
							.setMessage("Adjustment Deduction Exceeding Maximum Number Of Quantities On Hand");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(
										final DialogInterface dialog,
										final int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
		}
	};

	protected void updateTotAmountdelUpdate() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		// **************Adjust Summary********************
		Cursor saveStockAdjustmentMain = null;
		try {
			saveStockAdjustmentMain = mydb.query(TEMP_ADJUSTMENT_SUMMARY, null,
					"username='" + currentUserStLoad
							+ "' AND currentState='9' AND AdjustTxnType='51'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (saveStockAdjustmentMain != null) {
			if (saveStockAdjustmentMain.getCount() > 0) {
				if (saveStockAdjustmentMain.moveToNext()) {
					currentSumID = saveStockAdjustmentMain.getString(0);
					String currentTotStr = saveStockAdjustmentMain.getString(8);
					Double currentTotVal = Double.parseDouble(currentTotStr);

					if (ONITEMUPDATE == 54) {
						adjustedTotVal = ((currentTotVal + TotalLoadingValue) - currentAdjustValUpdate);
						Log.v(TAG, "PRINT_CAL SUM:(" + currentTotVal + "+"
								+ TotalLoadingValue + "-"
								+ currentAdjustValUpdate + ")");

					} else if (ONITEMDEL == 64) {
						adjustedTotVal = currentTotVal - currentAdjustValUpdate;
						Log.v(TAG, "PRINT_CAL SUM DEL:(" + currentTotVal + "-"
								+ currentAdjustValUpdate);
					}

					ContentValues valueupdateStsummary = new ContentValues();
					valueupdateStsummary.put("TotalAmount", adjustedTotVal);
					mydb.update(TEMP_ADJUSTMENT_SUMMARY, valueupdateStsummary,
							"adjustsum_id=" + currentSumID, null);
				}
			}
		}

		// -------------Adjust header------------
		String onUpDelRefNo = btnstadjustingrefno.getText().toString();
		Cursor saveStockAdjustmenthead = null;
		try {
			saveStockAdjustmenthead = mydb.query(ADJUST_ADDITION_HEADER, null,
					"AddUser='" + currentUserStLoad + "' AND RefNo='"
							+ onUpDelRefNo + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (saveStockAdjustmenthead != null) {
			if (saveStockAdjustmenthead.getCount() > 0) {
				if (saveStockAdjustmenthead.moveToNext()) {
					currenthedID = saveStockAdjustmenthead.getString(0);
					String currentTotStr = saveStockAdjustmenthead.getString(8);
					Double currentTotVal = Double.parseDouble(currentTotStr);

					if (ONITEMUPDATE == 54) {
						adjustedTotVal = ((currentTotVal + TotalLoadingValue) - currentAdjustValUpdate);
						Log.v(TAG, "PRINT_CAL HED:(" + currentTotVal + "+"
								+ TotalLoadingValue + "-"
								+ currentAdjustValUpdate + ")");

					} else if (ONITEMDEL == 64) {
						adjustedTotVal = currentTotVal - currentAdjustValUpdate;
						Log.v(TAG, "PRINT_CAL SUM DEL:(" + currentTotVal + "-"
								+ currentAdjustValUpdate);
					}
					ContentValues valueupdateSthed = new ContentValues();
					valueupdateSthed.put("TotalAmt", adjustedTotVal);
					mydb.update(ADJUST_ADDITION_HEADER, valueupdateSthed,
							"fadjhed_id=" + currenthedID, null);
				}
			}
		}

	}

	protected void ensbleAndDisButtons() {
		// TODO Auto-generated method stub
		dmstockadjustmentadd.setEnabled(true);
		dmstockadjustmentdelete.setEnabled(false);
		dmstockadjustmentupdate.setEnabled(false);
	}

	// ======Save new Adjustment Addition Record in to Details & Header Table
	protected void saveNewAdjustmentAddition() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		checkNewSequence();

		// Pre Calculations for cases Pieces
		String casePieces = etdmstadjustingitemcaseunit.getText().toString();
		casePieQtyValue = Integer.parseInt(casePieces);

		if (etdmstadjustingitemcases.length() != 0) {
			String caseQtyStr = etdmstadjustingitemcases.getText().toString();
			caseQtyValue = Integer.parseInt(caseQtyStr);
		}
		if (etdmstadjustingitempieces.length() != 0) {
			String piecesQtyStr = etdmstadjustingitempieces.getText()
					.toString();
			casePiecesValue = Integer.parseInt(piecesQtyStr);
		}
		if (casePiecesValue >= casePieQtyValue) {
			Integer newCasesQty = casePiecesValue / casePieQtyValue;
			caseQtyValue = caseQtyValue + newCasesQty;

			casePiecesValue = (casePiecesValue - (newCasesQty * casePieQtyValue));
		}

		try {
			ContentValues addnewAdjustmentDetails = new ContentValues();
			addnewAdjustmentDetails.put("RefNo", btnstadjustingrefno.getText()
					.toString());
			addnewAdjustmentDetails.put("TxnDate", etdmstadjustingdate
					.getText().toString());
			addnewAdjustmentDetails.put("TxnType", "51");
			addnewAdjustmentDetails.put("SeqNo", invDetLastSequence);
			addnewAdjustmentDetails.put("ItemCode", stLoaditemcode);

			// Calculate Total Quantity in cases and pieces
			caseItemsQtyVal = Integer.toString(caseQtyValue);
			piecesQtyVal = Integer.toString(casePiecesValue);

			String caseUnitsVal = etdmstadjustingitemcaseunit.getText()
					.toString();
			String pieceAmount = etdmstadjustingitemprice.getText().toString();
			double caseValue = Double.parseDouble(caseItemsQtyVal);
			double piecesValue = Double.parseDouble(piecesQtyVal);
			double unitsValue = Double.parseDouble(caseUnitsVal);
			double pieceAmountValue = Double.parseDouble(pieceAmount);
			double TotalPiecesQTY = (caseValue * unitsValue) + piecesValue;
			String PrintTotalPiecesQTY = Double.toString(TotalPiecesQTY);
			TotalAmountCurrentAdjust = pieceAmountValue * TotalPiecesQTY;
			PrintTotalAmount = Double.toString(TotalAmountCurrentAdjust);
			addnewAdjustmentDetails.put("CaseQty ", caseItemsQtyVal);
			addnewAdjustmentDetails.put("PiceQty ", piecesQtyVal);
			addnewAdjustmentDetails.put("Qty ", PrintTotalPiecesQTY);
			addnewAdjustmentDetails.put("CostPrice",
					PrintcurrentUnitPriceAverage);
			addnewAdjustmentDetails.put("Amt ", PrintTotalAmount);
			addnewAdjustmentDetails.put("ReaCode ", reasonCode);
			addnewAdjustmentDetails.put("ItemName ", etdmstadjustingitemname
					.getText().toString());
			addnewAdjustmentDetails.put("QOH ", etdmstadjustingqoh.getText()
					.toString());
			addnewAdjustmentDetails.put("ReaName ", etdmadjustmentreason
					.getText().toString());
			addnewAdjustmentDetails.put("CaseUnits ",
					etdmstadjustingitemcaseunit.getText().toString());
			addnewAdjustmentDetails.put("CasePrice ", etdminvdunitpriceval
					.getText().toString());
			addnewAdjustmentDetails.put("adjDetSync ", "0");
			mydb.insert(ADJUST_ADDITION_DETAILS, null, addnewAdjustmentDetails);

		} catch (Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
		// Records Details to Header
		insertUpdateAdjustHeader();
		// Records Details to Details
		updateAdjustingSummary();
		ListAdjustingItems();
		mydb.close();
	}

	private void insertUpdateAdjustHeader() {
		// TODO Auto-generated method stub
		String AdjustRefNo = btnstadjustingrefno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkUpdateAdjustHeader = null;
		try {
			checkUpdateAdjustHeader = mydb.query(ADJUST_ADDITION_HEADER, null,
					"AddUser='" + currentUserStLoad + "' AND RefNo='"
							+ AdjustRefNo.trim() + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (checkUpdateAdjustHeader != null) {
			if (checkUpdateAdjustHeader.getCount() > 0) {
				while (checkUpdateAdjustHeader.moveToNext()) {

					String adjhedrecid = checkUpdateAdjustHeader.getString(0);
					String currentTotAmount = checkUpdateAdjustHeader
							.getString(8);
					double currentTotAmountVal = Double
							.parseDouble(currentTotAmount);
					double AdjustTotalAmtSum = TotalAmountCurrentAdjust
							+ currentTotAmountVal;

					ContentValues valueupdateStlHead = new ContentValues();

					valueupdateStlHead.put("LocCode ", CurrentLocCode);
					valueupdateStlHead.put("ManuRef ", etdmstadjustingmanuno
							.getText().toString());
					valueupdateStlHead.put("TotalAmt", AdjustTotalAmtSum);
					mydb.update(ADJUST_ADDITION_HEADER, valueupdateStlHead,
							"fadjhed_id=" + adjhedrecid, null);

				}
			} else {
				ContentValues addnewAdjustmentHeader = new ContentValues();
				addnewAdjustmentHeader.put("RefNo", btnstadjustingrefno
						.getText().toString());
				addnewAdjustmentHeader.put("TxnDate", etdmstadjustingdate
						.getText().toString());
				addnewAdjustmentHeader.put("CostCode", "000");
				addnewAdjustmentHeader.put("ManuRef", etdmstadjustingmanuno
						.getText().toString());
				addnewAdjustmentHeader.put("DealCode", controlDealCode);
				addnewAdjustmentHeader.put("RefNo2", "");
				addnewAdjustmentHeader.put("TxnType", "51");
				addnewAdjustmentHeader.put("TotalAmt", PrintTotalAmount);
				addnewAdjustmentHeader.put("Remarks", etdmstadjustingremark
						.getText().toString());
				addnewAdjustmentHeader.put("LocCode", CurrentLocCode);
				addnewAdjustmentHeader.put("ReaCode", reasonCode);
				addnewAdjustmentHeader.put("GlPost", "");
				addnewAdjustmentHeader.put("GlBatch", "");
				addnewAdjustmentHeader.put("AddUser", currentUserStLoad);
				addnewAdjustmentHeader.put("AddDate", getAddDateTimeString().toString());
				addnewAdjustmentHeader.put("AddMach", currentUserStLoad);
				addnewAdjustmentHeader.put("ItemType", "0");
				addnewAdjustmentHeader.put("adjHedSync", "0");
				mydb.insert(ADJUST_ADDITION_HEADER, null,
						addnewAdjustmentHeader);
			}
		}
		checkUpdateAdjustHeader.close();
		mydb.close();
	}

	private void updateAdjustingSummary() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkUpdateAdjustSummary = null;
		try {
			checkUpdateAdjustSummary = mydb.query(TEMP_ADJUSTMENT_SUMMARY,
					null, "username='" + currentUserStLoad
							+ "' AND currentState='9' AND AdjustTxnType='51'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (checkUpdateAdjustSummary != null) {
			if (checkUpdateAdjustSummary.getCount() > 0) {
				while (checkUpdateAdjustSummary.moveToNext()) {
					String adjsumrecid = checkUpdateAdjustSummary.getString(0);
					String currentTotAmount = checkUpdateAdjustSummary
							.getString(8);
					double currentTotAmountVal = Double
							.parseDouble(currentTotAmount);
					double AdjustTotalAmtSum = TotalAmountCurrentAdjust
							+ currentTotAmountVal;

					ContentValues valueupdateAdjustSummary = new ContentValues();

					valueupdateAdjustSummary.put("LocCode ", CurrentLocCode);
					valueupdateAdjustSummary.put("LocName ",
							etstockadjustmentFLoc.getText().toString());
					valueupdateAdjustSummary.put("ManuRefNo ",
							etdmstadjustingmanuno.getText().toString());
					valueupdateAdjustSummary.put("TotalAmount ",
							AdjustTotalAmtSum);

					mydb.update(TEMP_ADJUSTMENT_SUMMARY,
							valueupdateAdjustSummary, "adjustsum_id ='"
									+ adjsumrecid + "'", null);
				}
			}
		}
		checkUpdateAdjustSummary.close();
		mydb.close();
	}

	// List Adjustment Items from Details table
	private void ListAdjustingItems() {
		currentAdjustRefCode = btnstadjustingrefno.getText().toString();
		// TODO Auto-generated method stub
		SimpleAdapter adaptertrdes = null;
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockadjustmentdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colstloaddes_1", "colstloaddes_2",
				"colstloaddes_3", "colstloaddes_4" };
		int[] totrdes = new int[] { R.id.stloaditemrefdet,
				R.id.stloadpiecevalue, R.id.stloadcasevalue,
				R.id.btnstloaditemrefdet };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };
		String col = "ItemCode";
		try {
			allrowitemsdes = mydb.query(ADJUST_ADDITION_DETAILS, null,
					"RefNo='" + currentAdjustRefCode + "'", null, null, null,
					null);

		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String adjrecid = allrowitemsdes.getString(0);
					String ItemCode = allrowitemsdes.getString(5);
					String CaseQty = allrowitemsdes.getString(6);
					String PiceQty = allrowitemsdes.getString(7);
					String QTY = allrowitemsdes.getString(8);
					String CostPrice = allrowitemsdes.getString(9);
					String ReaCode = allrowitemsdes.getString(11);
					String ItemName = allrowitemsdes.getString(12);
					String QOH = allrowitemsdes.getString(13);
					String ReaName = allrowitemsdes.getString(14);
					String CaseUnits = allrowitemsdes.getString(15);
					String CasePrice = allrowitemsdes.getString(16);
					String rawitemsdet = adjrecid + "/" + ItemCode + "/"
							+ CaseQty + "/" + PiceQty + "/" + CostPrice + "/"
							+ ReaCode + "/" + ItemName + "/" + QOH + "/"
							+ ReaName + "/" + CaseUnits + "/" + CasePrice;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colstloaddes_1", ItemName);
					maptrdes.put("colstloaddes_2", CaseQty);
					maptrdes.put("colstloaddes_3", PiceQty);
					maptrdes.put("colstloaddes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
						R.layout.dm_adjustment_list_raw, fromtrdes, totrdes);

				lvtypedes.setAdapter(adaptertrdes);
			}
			int recRemCount = allrowitemsdes.getCount();
			if (recRemCount == 0 && DELTAG == 88) {
				Intent myIntent = new Intent(this, DM_AdjustmentDeduction.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				DELTAG = 0;
				finish();
			} else if (recRemCount == 0 && CLEARTAG == 22) {
				Intent myIntent = new Intent(this, DM_AdjustmentDeduction.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				CLEARTAG = 0;
				finish();
			}
		}
		clearFieldsAdjustment();
		allrowitemsdes.close();
		mydb.close();
	}

	private void clearFieldsAdjustment() {
		// TODO Auto-generated method stub
		caseQtyValue = 0;
		casePiecesValue = 0;
		casePieQtyValue = 0;
		if (CLEARTAG == 22) {
			etdmstadjustingmanuno.setText("");
			etstockadjustmentFLoc.setText("");
			etdmstadjustingremark.setText("");
			etdmadjustmentreason.setText("");
		}
		// etdmstadjustingmanuno.setText("");

		etdmstadjustingitemname.setText("");
		etdmstadjustingqoh.setText("");
		etdmstadjustingitemcaseunit.setText("");
		etdmstadjustingitemprice.setText("");
		etdminvdunitpriceval.setText("");
		etdmstadjustingitemcases.setText("");
		etdmstadjustingitempieces.setText("");
		// etdmadjustmentreason.setText("");
		caseItemsQtyVal = "0";
		piecesQtyVal = "0";
		PrintTotalAmount = "0.0";
		TotalAmountCurrentAdjust = 0.0;
		ONITEMUPDATE = 0;
		ONITEMDEL = 0;
		adjustedTotVal = 0;
		currentAdjustVal = 0;
	}

	private void checkNewSequence() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		String query = "SELECT fadjdet_id from FAdjDet order by fadjdet_id DESC limit 1";
		Cursor c = mydb.rawQuery(query, null);
		if (c != null && c.moveToLast()) {
			lastId = c.getLong(0);
			strlastId = Long.toString(lastId);
		}
		Cursor chkItemSequence = null;
		try {
			chkItemSequence = mydb.query(ADJUST_ADDITION_DETAILS, null,
					"fadjdet_id='" + strlastId + "'", null, null, null, null);
		} catch (Exception e1) {
		}

		try {
			if (chkItemSequence != null) {
				if (chkItemSequence.getCount() > 0) {
					while (chkItemSequence.moveToNext()) {
						String rawid = chkItemSequence.getString(0);
						invDetLastRefNo = chkItemSequence.getString(1);
						String strinvDetLastSequence = chkItemSequence
								.getString(4);
						invDetLastSequence = Integer
								.parseInt(strinvDetLastSequence);
						if (invDetLastRefNo.equals(currentAdjustRefCode)) {
							invDetLastSequence = invDetLastSequence + 1;
						} else {
							invDetLastSequence = 1;
						}
					}
				} else {
					invDetLastSequence = 1;
				}
			} else {
				invDetLastSequence = 1;
			}

		} catch (Exception e1) {
			Toast.makeText(getApplicationContext(), "Error Select Sequence..",
					Toast.LENGTH_SHORT).show();
		}
		chkItemSequence.close();
		mydb.close();
	}

	// -------View current Adjustment Details
	private void viewCurrentAdjustmetRecords() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkCurrentAdjustment = null;
		try {
			checkCurrentAdjustment = mydb.query(TEMP_ADJUSTMENT_SUMMARY, null,
					"username='" + currentUserStLoad
							+ "' AND currentState='9' AND AdjustTxnType='51'",
					null, null, null, null);
		} catch (Exception e) {
		}

		if (checkCurrentAdjustment != null) {
			if (checkCurrentAdjustment.getCount() > 0) {
				while (checkCurrentAdjustment.moveToNext()) {
					String AdjustmentRefNo = checkCurrentAdjustment
							.getString(2);
					CurrentLocCode = checkCurrentAdjustment.getString(6);
					String CurrentLocName = checkCurrentAdjustment.getString(7);
					String CurrentManuRef = checkCurrentAdjustment.getString(9);
					btnstadjustingrefno.setText(AdjustmentRefNo);
					etdmstadjustingdate.setText(getCurrentTimeString()
							.toString());
					etdmstadjustingmanuno.setText(CurrentManuRef);
					etstockadjustmentFLoc.setText(CurrentLocName);
					ListAdjustingItems();
				}
			}
		}
		checkCurrentAdjustment.close();
		mydb.close();
	}

	private void createNewAdjustmentAddition() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		newAdjustmenrRefNoCode = StlTransTypePrefix.trim()
				+ stlAgentPrefixType.trim() + currentUserPrefixLoad;
		try {
			ContentValues addnewAdjustment = new ContentValues();
			addnewAdjustment.put("username", currentUserStLoad);

			try {
				if (strLatestAdjustSerial.length() == 1) {
					String newInvNumberStr = "00000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 2) {
					String newInvNumberStr = "0000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 3) {
					String newInvNumberStr = "000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 4) {
					String newInvNumberStr = "00" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 5) {
					String newInvNumberStr = "0" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			addnewAdjustment.put("refSerial", strLatestAdjustSerial);
			addnewAdjustment.put("refCode", currentAdjustRefCode);
			addnewAdjustment.put("currentState", "9");
			addnewAdjustment.put("activeMode", "0");
			addnewAdjustment.put("LocCode", "0");
			addnewAdjustment.put("LocName", "");
			addnewAdjustment.put("TotalAmount", "0.0");
			addnewAdjustment.put("ManuRefNo", "");
			addnewAdjustment.put("AdjustTxnType", "51");
			mydb.insert(TEMP_ADJUSTMENT_SUMMARY, null, addnewAdjustment);

		} catch (Exception e) {
			// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
		// updateFcompanyBranch();
		// print latest adjust ref no
		btnstadjustingrefno.setText(currentAdjustRefCode);
		etdmstadjustingdate.setText(getCurrentTimeString().toString());
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {

					currentUserStLoad = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(3);
				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Agent Prefix
	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
					controlDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Trans Type
	private void stLoadingTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("SADJD")) {
						StlTransTypePrefix = cCharValue.trim();
					}
				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Trans Type
	private void checkLatestAdjustmentSerial() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAdjustSerial = null;

		try {
			selectAdjustSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='SADJD' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}

		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_ADJUSTMENT_SUMMARY, null,
					"username='" + currentUserStLoad
							+ "' AND currentState='9' AND AdjustTxnType='51'",
					null, null, null, null);
		} catch (Exception e) {
		}

		if (selectAdjustSerial != null) {
			if (selectAdjustSerial.getCount() > 0) {
				while (selectAdjustSerial.moveToNext()) {
					String cSettingsCode = selectAdjustSerial.getString(3);
					String nNumVal = selectAdjustSerial.getString(4);
					strLatestAdjustSerial = nNumVal.trim();
					if (selectLastinvrec != null) {
						if (selectLastinvrec.getCount() > 0) {
							if (selectLastinvrec.moveToLast()) {
								viewCurrentAdjustmetRecords();
							}
						} else if (selectLastinvrec.getCount() <= 0) {
							createNewAdjustmentAddition();
						}
					}
				}
			} else {
				strLatestAdjustSerial = "1";
				try {
					ContentValues newAdjustment = new ContentValues();
					newAdjustment.put("BranchCode", currentUserStLoad);
					newAdjustment.put("RecordId", "1");
					newAdjustment.put("cSettingsCode", "SADJD");
					newAdjustment.put("nNumVal", strLatestAdjustSerial);
					mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);
					createNewAdjustmentAddition();
				} catch (Exception e) {
					// Toast.makeText(this, e.toString(),
					// Toast.LENGTH_LONG).show();
				}
				mydb.close();
			}
		}
		selectAdjustSerial.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Stock Load Location List
	private void populateStockLoadLocationList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewLocationList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invstloclocationname,
				R.id.invstloclocationdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(ITEM_LOCATION, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String LocCode = allrowtypedes.getString(9);
					String LocName = allrowtypedes.getString(10);
					String LoctCode = allrowtypedes.getString(11);

					String columnfLocdet = LocCode + "/" + LocName + "/"
							+ LoctCode;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", LocCode + " - " + LocName);
					maptrdes.put("coldes_2", columnfLocdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_stock_locations_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Stock Load Items List
	@SuppressLint("NewApi")
	private void populateItemsDetailsList() {
		// TODO Auto-generated method stub
		Cursor cursor = dbHelper.fetchAllItems();

		// The desired columns to be bound
		String[] columns = new String[] { DM_ItemsList_Adapter.KEY_ITEMCODE,
				DM_ItemsList_Adapter.KEY_ITEMNAME };

		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.invoiceitemsdet, R.id.invitemsname, };

		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapter = new SimpleCursorAdapter(this,
				R.layout.dm_location_items_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listviewStLoadItemsList);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapter);

		EditText myFilter = (EditText) findViewById(R.id.dminvfilteritems);
		myFilter.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapter.getFilter().filter(s.toString());
			}
		});

		dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			public Cursor runQuery(CharSequence constraint) {
				return dbHelper.fetchItemsByName(constraint.toString());
			}
		});
	}

	// Populate resons list summary
	private void populateReasonsDetailsList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewReasonsDetails);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.recreasonsdet, R.id.receiptreasonname };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curPopItemsListDet = null;
		try {
			curPopItemsListDet = mydb.query(SALES_ORD_REASON, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (curPopItemsListDet != null) {
			if (curPopItemsListDet.getCount() > 0) {
				while (curPopItemsListDet.moveToNext()) {
					String ReaCode = curPopItemsListDet.getString(4);
					String ReaName = curPopItemsListDet.getString(5);

					String rawreasondet = ReaCode + "/" + ReaName;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawreasondet);
					maptrdes.put("coldes_2", ReaName);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_reasons_list_raw, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curPopItemsListDet.close();
		mydb.close();
	}

	// Check and print current time

	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		// SimpleDateFormat dfcus = new
		// SimpleDateFormat("yyyy-MM-dd 00:00:00.000");
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		// String cusDate = date_to_string + " " + "00:00:00.000";
		String cusDate = date_to_string;
		// String formattedDatecustom = dfcus.format(c.getTime());
		return cusDate;
	}

	// *************Check Pieces Quantity With Case Units**********************
	private TextWatcher checkPiecesValidation = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			if (etdmstadjustingitempieces.length() != 0) {
				if (etdmstadjustingitemcaseunit.length() != 0) {
					double CurrentCasesVal = 0.0, CaseUnitAmountVal = 0.0, CurrentPirecesVal = 0.0, CurrentQohVal = 0.0, CurrentCasesPiecesVal = 0.0;
					String CaseUnitAmount = etdmstadjustingitemcaseunit
							.getText().toString();
					String CurrentPireces = etdmstadjustingitempieces.getText()
							.toString();
					String CurrentQoh = etdmstadjustingqoh.getText().toString();

					if (etdmstadjustingitemcases.length() != 0) {
						String CurrentCases = etdmstadjustingitemcases
								.getText().toString();
						CurrentCasesVal = Double.parseDouble(CurrentCases);
					}

					CaseUnitAmountVal = Double.parseDouble(CaseUnitAmount);
					CurrentPirecesVal = Double.parseDouble(CurrentPireces);

					CurrentQohVal = Double.parseDouble(CurrentQoh);
					CurrentCasesPiecesVal = CurrentCasesVal * CaseUnitAmountVal;
					double currentTotPieces = CurrentCasesPiecesVal
							+ CurrentPirecesVal;

					if (CurrentQohVal < currentTotPieces) {
						etdmstadjustingitempieces.setText("");
						etdmstadjustingitemcases.setText("");
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_AdjustmentDeduction.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("INVALID ADJUSTMENT");
						// Setting Dialog Message
						alertDialog
								.setMessage("Adjustment Exceeding Maximum Number Of Quantities On Hand");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(
											final DialogInterface dialog,
											final int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}
					/*
					 * if (CaseUnitAmountVal <= CurrentPirecesVal) {
					 * Toast.makeText(getApplicationContext(),
					 * "Maximum Items Pieces:" + CaseUnitAmount,
					 * Toast.LENGTH_SHORT).show();
					 * etdmstadjustingitempieces.setText(""); }
					 */

				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

	};

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SAVE_STOCK_LOADING:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_save_adjustment, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder
					.setTitle("Stock Adjustment Deduction Saved Successfully..");
			dialogbuilder.setView(dialogview);
			StockLoadingAlert = dialogbuilder.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_CANCEL_STOCK_LOADING:
			LayoutInflater inflaterstl = LayoutInflater.from(this);
			View dialogviewstl = inflaterstl.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilderstl = new AlertDialog.Builder(this);
			dialogbuilderstl.setTitle("Cancel Stock Adjustment Deduction...");
			dialogbuilderstl.setView(dialogviewstl);
			StockLoadingAlert = dialogbuilderstl.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_UNDO_STOCK_LOADING:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu
					.setTitle("Undo Current Stock Adjustment Deduction...");
			dialogbuilderu.setView(dialogviewu);
			StockLoadingAlert = dialogbuilderu.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_PRINT_STOCK_LOADING:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			StockLoadingAlert = dialogbuilderp.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		}

		return StockLoadingAlert;

	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
}
